<?php

namespace app\index\controller;

use addons\wechat\model\WechatCaptcha;
use app\common\controller\Frontend;
use app\common\library\Ems;
use app\common\library\Sms;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;
use think\Db;

//设置的数量在shower  和女浴室的数量在一个表
use app\common\model\ShowerSetting;


use app\common\model\BathRecord;

/**
 * 男浴室申请
 */
class Bath extends Frontend
{

    protected $noNeedLogin = ['index','check', 'into', 'leave'];
    protected $noNeedRight = ['*'];
    protected $layout = 'weiui';

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;
    }

    /**
     * 空的请求
     * @param $name
     * @return mixed
     */
    public function _empty($name)
    {
        $data = Hook::listen("user_request_empty", $name);
        foreach ($data as $index => $datum) {
            $this->view->assign($datum);
        }
        return $this->view->fetch('user/' . $name);
    }

    /**
     * 预约登记
     */
    public function index()
    {
        //获取预约总数，剩余数量
        $id = 2;
        $row = ShowerSetting::get($id);

        $this->assign('pageTitle','东苑男生浴池');
        $url = $this->request->request('url', '');
        if ($this->request->isPost()) {

            $username = $this->request->post('username');
            $sid = $this->request->post('sid');

            $rule = [
                'username'  => 'require|length:2,20',
                'sid'  => 'require|length:8,30',
            ];

            $msg = [
                'username.require'  => 'Username can not be empty',
                'username.length'   => 'Username must be 2 to 20 characters',
                'sid.require' => 'sid can not be empty',
                'sid.length'  => 'sid must be 8 to 30 characters',
            ];

            $data = [
                'username'  => $username,
                'sid'  => $sid,
            ];
    
            //获取开始预约时间，和结束预约时间
            $begin_time= Config::get('site.expire_begin_time');//开始时间
            $begin_fen= Config::get('site.expire_begin_fen');//开始分钟

            $begin_times = strtotime($begin_time.':'.$begin_fen);


            $end_time= Config::get('site.expire_end_time');//结束时间
            $end_fen= Config::get('site.expire_end_fen');//结束分钟

            $end_times = strtotime($end_time.':'.$end_fen);
            //echo $end_times."###<br/>";

            //获取当前的时分
            $local_time = strtotime(date("H:i"));

            if($local_time<$begin_times||$local_time>$end_times)
            {
                $this->error(__('Appointment time not reached'));
            }
                
            ////判断预约数量是否为0
            //预约已满请稍候再试
            if($row['showered_number']==0){
                $this->error(__('Reservation full please try again later'));
            }

            //不算本次添加，计算有几次忘记。离开的时候未扫码
            $count  = BathRecord::where(['nickname' => $username, 'sid' => $sid,'into_states'=>1,'leave_states'=>0])->count();

            $result = $this->auth->bath($username,$sid);
            if ($result) {

                $where_['nickname']= $username;
                $where_['sid']=$sid;
                $where_['states']=1;

                $info= Db::name('bath_record')->where($where_)->find();

                if(empty($row['showered_number'])){
                    $row-> showered_number = $row['shower_number']-1;
                }else{
                    $row-> showered_number = $row['showered_number']-1;
                }
                $row-> add_time = time();
                $row->save();
            
                //从site.php 文件中获取
                $reserve_expire_time= Config::get('site.reserve_expire_time');
                $add_time= date('Y-m-d H:i:s',$info['add_time']);
                $data['times'] = $reserve_expire_time;
                $data['add_time']= $add_time;
                //提示进入时间
                // 当前时间戳 格式：2019-03-13 18:00:00 
                // echo date('Y-m-d H:i:s', time())."####<br/>"; 
                $data['in_time'] = date('Y-m-d H:i:s', strtotime('+'.$reserve_expire_time.'minute',$info['add_time']));
                // exit();

                //获取该学生是否有离开忘记扫码的情况
                $data['count'] = $count;

                $this->success(__('预约成功'), $url ? $url : url('user/index'),$data);                
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('row',$row);
        
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch();
    }


    /**
     * 预约登记
     */
    public function check()
    {
        $this->assign('pageTitle','东苑男生浴池');
        $url = $this->request->request('url', '');
        if ($this->request->isPost()) {

            $username = $this->request->post('username');
            $sid = $this->request->post('sid');

            $where_['nickname']= $username;
            $where_['sid']=$sid;
            //$where_['states']=1;
            $where_['into_states']=0;//未进入

            $info= Db::name('bath_record')->where($where_)->order('id desc')->find();
            if ($info) {

                //定时任务已经改为过期
                if($info['states']==2)
                {
                    $this->error('预约已过期,请重新预约');
                }
                //从site.php 文件中获取
                //验证预约时间是否过期了
                $reserve_expire_time= Config::get('site.reserve_expire_time');

                $minute=floor((time()-$info['add_time'])%86400/60);
                //echo "相差分钟数：".$minute."分钟<br/><br/>";
                
                $timediff = time()-$info['add_time'];
                $days = intval($timediff/86400);

                //计算相差的时间为$site_time以上，就改为过期。
                if($minute>$reserve_expire_time||$days!=0)
                {
                    //更新为已过期
                    $row = BathRecord::get($info['id']);
                    $row-> states = 2;
                    $row->save();

                    //释放预约数量
                    $id = 2;
                    $sult = ShowerSetting::find($id);
                    if($sult){
                        $finy = ($sult['showered_number']+1);
                        //如果添加上1，大于总数，就把总数给变量数
                        if($finy<$sult['shower_number']){
                            $sult -> showered_number = $finy;
                        }else{
                            $sult -> showered_number = $sult['shower_number'];
                        }
                        $sult -> save();
                    }

                    $this->error('预约已过期,请重新预约');
                }
                $add_time= date('Y-m-d H:i:s',$info['add_time']);
                $data['times'] = $reserve_expire_time;
                $data['in_time'] = date('Y-m-d H:i:s', strtotime('+'.$reserve_expire_time.'minute',$info['add_time']));
                $data['add_time']= $add_time;
                $this->success(__('预约成功'), $url ? $url : url('user/index'),$data);                
            } else {

                $this->error('还未预约，请先预约', null, ['token' => $this->request->token()]);
            }
        }
    }


    /**
     * 进入浴池
     *
     * @param string $username  账号
     * @param string $sid 学号
     */    
    public function into()
    { 
        $this->assign('pageTitle','东苑男生浴池'); 
        $url = $this->request->request('url', '');        
        if ($this->request->isPost())
        {
            $username = $this->request->post('username');
            $sid = $this->request->post('sid');

            $where['nickname'] = $username;
            $where['sid'] = $sid;
            //$where['into_states'] = 0;
            //$where['leave_states'] = 0;
            $row = BathRecord::where($where)->order('id desc')->find();

            if(!empty($row)){
                if($row['states']==1){

                    //已进入，未离开
                    if($row['into_states']==1&&$row['leave_states']==0)
                    {
                        $this->error('在浴室中,还未离开');
                    }
                    //从site.php 文件中获取
                    //验证预约时间是否过期了
                    $reserve_expire_time= Config::get('site.reserve_expire_time');

                    $minute=floor((time()-$row['add_time'])%86400/60);
                    //echo "相差分钟数：".$minute."分钟<br/><br/>";

                    $timediff = time()-$row['add_time'];
                    $days = intval($timediff/86400);

                    //计算相差的时间为$site_time以上，就改为过期。
                    if($minute>$reserve_expire_time||$days!=0)
                    {
                        //更新为已过期
                        $row = BathRecord::get($row['id']);
                        $row-> states = 2;
                        $row->save();

                        //释放预约数量
                        $id = 2;
                        $sult = ShowerSetting::find($id);
                        if($sult){
                            $finy = ($sult['showered_number']+1);
                            //如果添加上1，大于总数，就把总数给变量数
                            if($finy<$sult['shower_number']){
                                $sult -> showered_number = $finy;
                            }else{
                                $sult -> showered_number = $sult['shower_number'];
                            }
                            $sult -> save();
                        }

                        $this->error('预约已过期,请重新预约');
                    }                    

                    //处理进入状态
                    $params['into_time']= time();
                    $params['into_states']=1;
                    $row->save($params);
                    $this->success(__('Intoed in successful'));
                }else if($row['states']==0){
                    //还未预约
                    $this->error(__('Please make an appointment before entering'));
                }else{
                    //已过期，重新预约
                    $this->error(__('Appointment expired'));
                }                
            }else{
                $this->error(__('还未预约'));
            }

        }
        //获取预约总数，剩余数量
        // $id = 1;
        // $row = ShowerSetting::get($id);
        // $this->view->assign('row',$row);        
        $this->view->assign('url', $url);
        return $this->view->fetch(); 
    }

    /**
     * 离开浴池
     *
     * @param string $username  账号
     * @param string $sid 学号
     * 释放预约名额 
     */     
    public function leave()
    {
        //获取预约总数，剩余数量
        $id = 2;
        $info = ShowerSetting::get($id);

        $this->assign('pageTitle','东苑男生浴池'); 
        $url = $this->request->request('url', '');        
        if ($this->request->isPost())
        {
            $username = $this->request->post('username');
            $sid = $this->request->post('sid'); 

            $where['nickname'] = $username;
            $where['sid'] = $sid;
            // $where['states'] =0;
            $where['into_states']=1;
            $where['leave_states']=0;
            $row = BathRecord::where($where)->order('id desc')->find();

            if(!empty($row)){
                //处理离开状态，做记录。
                $params['leave_time']= time();
                $params['leave_states']=1;
                $params['states']=0;
                $row->save($params);

                //给shower表 释放记录，加回去一条记录
                //释放预约数量
                $finy = ($info['showered_number']+1);
                if($finy<$info['shower_number']){
                    $sult['showered_number'] = $finy;
                }else{
                    $sult['showered_number'] = $info['shower_number'];
                }
                $info -> save($sult);

                $this->success(__('Leaved in successful'));
            }else{
                //找不到这条记录，提示错误
                $this->error(__('先进入,再离开!'));            
            } 
        } 
        $this->view->assign('url', $url);
        return $this->view->fetch(); 
    }  

}
